<!-- subpkg_consult/room/index.vue -->
<script lang="ts" setup>
  import { orderDetailApi } from '@/api/order'
  import { useCounterStore } from '@/stores/counter'
  import type { OrderDetail } from '@/types/order'
  import { io, type Socket } from 'socket.io-client'
  import RoomStatus from './components/room-status.vue'
  import { ref } from 'vue'
  import type { MsgData, MsgItem } from '@/types/room'

  const store = useCounterStore()
  const props = defineProps<{
    orderId: string
    payResult: string
  }>()
  // 1. 处理支付失败
  if (props.payResult === 'false') {
    uni.switchTab({
      url: '/page/my/index',
    })
  }
  // 2. 建立连接
  const socket: Socket = io('https://consult-api.itheima.net', {
    auth: { token: 'Bearer ' + store.token },
    query: { orderId: props.orderId },
    transports: ['websocket', 'polling'],
    timeout: 5000,
  })
  socket.on('connect', () => {
    // 建立连接成功
    console.log('连接建立成功')
  })

  socket.on('error', (event) => {
    // 错误异常消息
    console.log('出现错误')
  })

  socket.on('disconnect', () => {
    // 已经断开连接
    console.log('断开连接')
  })
  // 问诊订单详情
  const orderDetail = ref({} as OrderDetail)
  const getOrderDetail = async () => {
    const data = await orderDetailApi(props.orderId)
    console.log('问诊订单详情：', data)
    orderDetail.value = data
  }
  getOrderDetail()
  //消息列表
  const messageList = ref<MsgItem[]>([])
  //获取历史消息
  socket.on('chatMsgList', (res: MsgData) => {
    //没有返回数据
    if (res.code !== 10000) return
    console.log('历史消息', res)
    //提取列表数据
    res.data?.forEach(({ item }) => {
      //追加到消息列表中
      messageList.value.push(...item!)
    })
  })
</script>

<template>
  <view class="room-page">
    <!-- 问诊订单状态 -->
    <room-status
      v-if="orderDetail?.id"
      :status-value="orderDetail.statusValue"
      :countdown="orderDetail.countdown"
      :status="orderDetail.status"
    />
    <scroll-view
      refresher-enabled
      refresher-background="#f2f2f2"
      scroll-y
      style="flex: 1; overflow: hidden"
    >
      <view class="message-container">
        <!-- 此处将来填充更多代码... -->
      </view>
    </scroll-view>

    <!-- 发送消息 -->
    <view class="message-bar">
      <template v-if="true">
        <uni-easyinput
          disabled
          :clearable="false"
          :input-border="false"
          placeholder-style="font-size: 32rpx; color: #c3c3c5;"
          placeholder="问医生"
        />
        <view class="image-button">
          <uni-icons size="40" color="#979797" type="image"></uni-icons>
        </view>
      </template>
      <button v-else class="uni-button">咨询其它医生</button>
    </view>
  </view>
</template>

<style lang="scss">
  @import './index.scss';
</style>
